package com.example.threadDemo;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
*基于框架集的ThreadPoolExecutor写的一个Demo
 */
public class ThreadPoolDemo {
    //写一个静态变量，这样就不用重复创建一个新的多线程队列了；新创建的话，因为一直等待任务，然后不能被GC，导致OOM
    public static ThreadPoolExecutor threadPoolExecutor=new ThreadPoolExecutor(3, 3,
            1L, TimeUnit.SECONDS,
            new ArrayBlockingQueue<Runnable>(5),  //固定长度
            new ThreadPoolExecutor.CallerRunsPolicy());    //默认抛弃方法

    public void run(final  Integer threadNum){
        try{
            threadPoolExecutor.submit(()->{
                System.out.println("ThreadRun"+threadNum);
            });
        }catch (RejectedExecutionException e){
            e.printStackTrace();
        }
    }

    public static void main(String[] args){
        System.out.println("main.start");
        ThreadPoolDemo threadPoolDemo=new ThreadPoolDemo();
        //模拟外面多次请求
        for(int i=0;i<=10;i++){
            System.out.println(i);
            threadPoolDemo.run(i);
        }
        System.out.println("main end");
    }
}
